<?php

namespace App\Service\UserCenter;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Helpers\RedisUtil;
use App\Model\CoinLog;
use App\Model\UserCoin;
use App\Model\UserProfilePersonal;
use App\Model\Withdraw;
use App\Service\BaseService;
use Hyperf\DbConnection\Db;

/**
 * 提现申请
 */
class WithdrawApplyService extends BaseService
{
    public function handle()
    {
        return $this->setError(ErrorCode::WITHDRAW_ERROR, '该版本暂不支持提现，请先升级到最新版本～');
        $userId = $this->getUserId();
        $withdrawRmb = $this->request->input('withdraw_rmb', 0);
        $version = $this->request->input('version', '');

        //加入同步锁
        if (RedisUtil::concurrentLock($key = "WithdrawApplyService_{$userId}", 3)) {
            log_info(__CLASS__ . "==withdraw_proccessing==Key:{$key}");
            return $this->setError(ErrorCode::OP_TOO_MANY, '操作太频繁，请勿重复提交！');
        }

        //是否实名认证
        $personalInfo = UserProfilePersonal::getProfile($userId);
        if (!UserProfilePersonal::isFaceVerified($personalInfo)) {
            log_info(__CLASS__ . "==NO_FACE_VRFY=={$userId}");
            return $this->setError(ErrorCode::NO_FACE_VRFY, '还未完成实名认证，无法申请提现');
        }

        $userCoin = UserCoin::getUserInfo($userId);
        $incomeCoin = $userCoin['income_coin'] ?? 0;
        //最大可提现
        $withdrawRmbLmt = Withdraw::getMaxRmbLimit($userId, $incomeCoin);
        if ($withdrawRmb > $withdrawRmbLmt || $withdrawRmb > Withdraw::WITHDRAW_DAY_MAX) {
            return $this->setError(ErrorCode::WITHDRAW_OVER_LMT, '提现超过限额，请重新输入~');
        }
        //非首次提现，只能提现N的整数倍
        $lastWithdraw = Withdraw::checkFirst($userId);
        if ($lastWithdraw) {
            if ($withdrawRmb % Withdraw::WITHDRAW_UNIT != 0) {
                return $this->setError(ErrorCode::WITHDRAW_ERROR, "非首次提现只能为" . Withdraw::WITHDRAW_UNIT . "的整数倍");
            }
            if ($withdrawRmb < 200) {
                return $this->setError(ErrorCode::WITHDRAW_ERROR, "非首次提现需要满200元哦～");
            }
            //今天已经申请过
            if ((string)$lastWithdraw->created_at > date('Y-m-d')) {
                return $this->setError(ErrorCode::WITHDRAW_ERROR, "今天已经申请过提现了哦，明天再来吧～");
            }
        }

        //计算扣除金币
        $withdrawCoin = Withdraw::transferToCoin($withdrawRmb);

        //实际到账金额
        if (Withdraw::checkFeeStart($version)) {
            $withdrawRmb = round($withdrawRmb * (1 - ConfigUtil::getWithdrawFeeRate()), 1);
        }

        Db::beginTransaction();
        try {
            //更新账户
            $remainCoin = UserCoin::decIncome($userId, $withdrawCoin);
            //添加流水记录
            CoinLog::addConsume(
                $userId,
                $withdrawCoin,
                CoinLog::FROM_WITHDRAW,
                $remainCoin
            );
            //记录
            Withdraw::addRecord($userId, $withdrawRmb, $withdrawCoin);
            Db::commit();
        } catch (\Throwable $exception) {
            log_info(__CLASS__ . '==withdraw==' . $exception->getMessage());
            Db::rollBack();
        }
        return ['result' => 1, 'tip' => '你的提现申请已提交，等待系统审核~'];
    }
}
